import oscP5.*;
import netP5.*;
import TUIO.*;

// Basic game components
Table table;
Game game;
TuioProcessing tuioClient;

// Miscellaneous global variables
int margin = 10;        // margin around the edges of the table
PFont mainFont;
int phase;              // between 0-15, for pulsing things, calculated for every frame
int endMsgLength = 300; // Time (in frames) that end message is visible

void setup() {
  size(screen.width,screen.height);
  tuioClient = new TuioProcessing(this);
  
  // Visual globals
  mainFont = loadFont("Dialog.bold-48.vlw"); 
  smooth();
  strokeCap(SQUARE);

  // Basic structures
  this.game = new Game();
  this.table = new Table(this.game);
  this.game.setUI(this.table);
  
  String[] params = { "C:/AaltoWindow/frameworks/java/processing/TuioOverlay.exe", "P5", frame.getTitle() };
  open(params);    

}

void draw() {
  background(255);
  phase = abs((frameCount % 90)/ 3 - 15);
  
  if(game.started) {
    game.frameUpdate();
    table.draw();
  } else {
    if(frameCount > game.endFrame + endMsgLength) {
      // Start game screen
      color textc = 180 + 2*phase;
      fill(textc);
      textFont(mainFont);
      textAlign(CENTER); 
      String s = "Touch screen to start a new game";
      text(s, margin, height/2, width-margin*2, height-margin*4);
    } else {
      // Game end message
      background(220);
      color textc = 70;
      fill(textc);
      textFont(mainFont);
      
      // Team A (left side)
      translate(width/5, height/2);
      rotate(HALF_PI);
      textAlign(CENTER); 
      String msgA = "WINNER";
      String msgB = msgA;
      if(game.teamLeft.score > game.teamRight.score) {
        msgB = "LOSER";
      } else if(game.teamLeft.score < game.teamRight.score) {
        msgA = "LOSER";
      } else {
        msgA = "DRAW";
        msgB = "DRAW";
      }
      text(msgA, 0, 0);
      
      // Team B (right side)
      rotate(-HALF_PI);
      translate(width/5*3, 0);
      rotate(-HALF_PI);
      text(msgB, 0, 0);
      
    }
  }
}

void stop() {
  super.stop();
}

// Entirely for testing purposes (artificial goals)
void keyPressed() {
  if (key == 'a' || key == 'A') {
    game.noMansLandPosition += (int)(width * 0.02);
  }
  if (key == 'b' || key == 'B') {
    game.noMansLandPosition -= (int)(width * 0.02);
  }
}

// General helper methods

boolean inTeamArea(int x, int y) {
  return inLeftTeamArea(x, y) || inRightTeamArea(x,y);
}

boolean inLeftTeamArea(int x, int y) {
  boolean inNoMansLand = x > (game.noMansLandPosition - game.noMansLandSize/2);
  boolean inMargin = x <= margin || x >= width-margin || y <= margin || y >= height-margin;
  return !inNoMansLand && !inMargin;
}

boolean inRightTeamArea(int x, int y) {
  boolean inNoMansLand = x < (game.noMansLandPosition + game.noMansLandSize/2);
  boolean inMargin = x <= margin || x >= width-margin || y <= margin || y >= height-margin;
  return !inNoMansLand && !inMargin;
}

